<?php

	/**
	 * @copyright Apache License 2.0
	 * @author Michael Giddens, SilverBiology
	 * @website http://code.google.com/p/species-land-management/
	*/
	session_start();
	set_time_limit( 180 );
	ini_set('memory_limit','32M');
	ini_set("display_errors", 1);
	$old_error_handler = set_error_handler("myErrorHandler");
	
	$expected = array(
			'cmd'
		,	'output'
		,	'filter'
		,	'sort'
		,	'dir'
		,	'start'
		,	'limit'
		,	'species_id'
		,	'event_id'
	);
	
	// Initialize allowed variables
	foreach ($expected as $formvar)
		$$formvar = (isset(${"_$_SERVER[REQUEST_METHOD]"}[$formvar])) ? ${"_$_SERVER[REQUEST_METHOD]"}[$formvar]:NULL;

	require_once("./config.php");
	require_once( BASE_PATH . "resources/api/classes/access_user/access_user_class.php");
	include_once( BASE_PATH . "resources/api/classes/class.floodblocker.php");
	require_once( BASE_PATH . "resources/api/classes/class.pugetsound.php");

	$ps = new PugetSound;
	$user_access = new Access_user;

# setting the rules for flood blocking
	$ps->flb->rules = array (
		10=>100,    // rule 1 - maximum 10 requests in 10 secs
		60=>400,    // rule 2 - maximum 40 requests in 60 secs
	/*	300=>50,   // rule 3 - maximum 50 requests in 300 secs
		3600=>200  // rule 4 - maximum 200 requests in 3600 secs*/
	);

	# Dos attack checking
	if (!$ps->flb->CheckFlood () ) {
		print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->flb->error(132) , 'code' => 132 ) ) ) );
		die();
	}

	// This is the output type that the program needs to return
	if(!isset($output)) {
		$output = "json";
	}
	
if($ps->load()) {
	$valid = true;
	switch( $cmd ) {

		case 'sign_in':
			$login = $_REQUEST['username'];
			$password = $_REQUEST['password'];
			$user_access->count_visit = true;
			$ret = $user_access->login_user($login,$password);
			if ($ret) {
				$land = array(1, 4);
				print_c( json_encode( array( 'success' => $ret, 'userLand' => $land ) ) );
			} else {
				print_c( json_encode( array( 'success' => $ret, 'error' => array('msg' => $user_access->the_msg, 'code' => 1 ) ) ) );
			}
			break;

		case 'sign_out':
			$user_access->log_out();
			print_c( json_encode( array( 'success' => true ) ) );

			break;

		case 'create_account':
			$login = $_REQUEST['login'];
			$password = $_REQUEST['password'];
			$confirm = $_REQUEST['confirm'];
			$name = $_REQUEST['name'];
			$info = @$_REQUEST['info'];
			$email = $_REQUEST['email'];

			$user_access->register_user($login, $password, $confirm, $name, $info, $email);
			print_c( json_encode( array( 'success' => true, 'message' => $user_access->the_msg ) ) );
			break;

		case 'activate':
			// task supporting email activation
			if (isset($_REQUEST['activate']) && isset($_REQUEST['ident'])) {
				$user_access->activate_account($_REQUEST['activate'], $_REQUEST['ident']);
				print_c( json_encode( array( 'success' => true, 'message' => $user_access->the_msg ) ) );
			} else {
				print_c( json_encode( array( 'success' => false ) ));
			}
			break;

		case 'forgot_password':
			$email = $_REQUEST['email'];
			$user_access->forgot_password($email);
			print_c( json_encode( array( 'success' => true, 'message' => $user_access->the_msg ) ) );
			break;

		case 'activate_password':
			// task to set activation string to session and to set the GUI for entering the new password
			if (isset($_REQUEST['activate']) && isset($_REQUEST['id'])) {
				if ($user_access->check_activation_password($_REQUEST['activate'], $_REQUEST['id'])) {
					$_SESSION['activation'] = $_REQUEST['activate'];
					$_SESSION['id'] = $_REQUEST['id'];
					print_c( json_encode( array( success => true ) ) );
				} else {
					print_c( json_encode( array( success => false ) ) );
				}
			}
			break;

		case 'activate_new_password':
			// task to set the new password coming from the GUI
			$user = $_REQUEST['user'];
			$password = $_REQUEST['password'];
			$confirm = $_REQUEST['confirm'];
			if ($user_access->activate_new_password( $password, $confirm, $_SESSION['activation'], $_SESSION['id'])) {
				unset($_SESSION['activation']);
				unset($_SESSION['id']);
			}
			$user_access->user = $user;
			print_c( json_encode( array( success => true, message => $user_access->the_msg ) ) );
			break;

		# commands
		case 'land-update':
			if(!$user_access->is_logged_in()) {$code = 2; $valid = false;}
			$data['land_id'] = $_REQUEST['land_id'];
			$data['polygon'] = $_REQUEST['polygon'];
			$data['description'] = $_REQUEST['description'];
			if (!$ps->land->_test->arg( array( &$data['private'] ) , array(  $_REQUEST['private'] ), 2, 0, array(0,1))) {
				$code = 6;
				$valid = false;
			}
			if (!$ps->land->_test->arg( array( &$data['title'] ) , array(  $_REQUEST['title'] ), 1)) {
				$code = 3;
				$valid = false;
			}

			if( trim($data['land_id']) != '' ) {
				if(!$ps->land->recordExists($data['land_id'])) {
					$code = 7;
					$valid = false;
				}
			}

			if($valid) {
				$ps->land->setData($data);
				$ps->land->save();
				print_c( json_encode( array( 'success' => true ) ) );
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;
			
		case 'land-list':
			$data['filter'] = json_decode( stripslashes($filter), true );
			if(trim($_REQUEST['sort']) != '') {
				$data['order'][] = array( 'field' => $_REQUEST['sort'], 'dir' => $_REQUEST['dir'] );
			}
			$ps->land->_test->arg( array( &$data['start'] ) , array(  $_REQUEST['start'] ), 2, '0' );
			$ps->land->_test->arg( array( &$data['limit'] ) , array(  $_REQUEST['limit'] ), 2, RECORDS_PER_PAGE );
			if($valid) {
				$ps->land->setData($data);
				$records = $ps->land->listRecords();
				$total = $ps->land->db->query_total();
				$records = ($records == NULL) ? array() : $records;
				print_c( json_encode( array( 'success' => true, 'total' => $total, 'records' => $records ) ) );
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		case 'land-getlist':
			if(!$ps->land->_test->arg( array( &$data['field'] ) , array(  $_REQUEST['field'] ), 2,  'title', array( 'polygon', 'title', 'description' ) )) {
				$valid = false;
				$code = 4;
			}
			$data['value'] = $_REQUEST['value'];
			if(!$ps->land->_test->arg( array( &$data['sort'] ) , array(  $_REQUEST['sort'] ), 2,  	'asc', array( 'asc', 'desc' ) )) {
				$valid =false;
				$code = 5;
			}
			$ps->land->_test->arg( array( &$data['start'] ) , array(  $_REQUEST['start'] ), 2, '0' );
			$ps->land->_test->arg( array( &$data['limit'] ) , array(  $_REQUEST['limit'] ), 2, RECORDS_PER_PAGE );
			$data["user_id"] = $_SESSION["user_id"];
			$data["showall"] = $_REQUEST["showall"];
			if($valid) {				
				$ps->land->setData($data);
				$records = $ps->land->getList();
				$records = ($records == NULL) ? array() : $records;
				print_c( json_encode( array( 'success' => true, 'records' => $records ) ) );
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		case 'event-update':
			if(!$user_access->is_logged_in()) {$code = 2; $valid = false;}
			$data['event_id'] = $_REQUEST['event_id'];
			$data['event_type_id'] = $_REQUEST['event_type_id'];
			$data['date_start'] = $_REQUEST['date_start'];
			$data['date_end'] = $_REQUEST['date_end'];
			$data['land_id'] = $_REQUEST['land_id'];
			$data['description'] = $_REQUEST['description'];
			if (!$ps->event->_test->arg( array( &$data['title'] ) , array(  $_REQUEST['title'] ), 1)) {
				$code = 3;
				$valid = false;
			}

			if( trim($data['event_id']) != '' && ($data['event_id'] != 0) ) {
				if(!$ps->event->recordExists($data['event_id'])) {
					$code = 7;
					$valid = false;
				}
			}

			if($valid) {
				$ps->event->setData($data);
				$ps->event->save();
				print_c( json_encode( array( 'success' => true ) ) );
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		case 'event-list':
			$data['filter'] = json_decode( stripslashes($filter), true );
			if(trim($_REQUEST['sort']) != '') {
				$data['order'][] = array( 'field' => $_REQUEST['sort'], 'dir' => $_REQUEST['dir'] );
			}
			$ps->event->_test->arg( array( &$data['start'] ) , array(  $_REQUEST['start'] ), 2, '0' );
			$ps->event->_test->arg( array( &$data['limit'] ) , array(  $_REQUEST['limit'] ), 2, RECORDS_PER_PAGE );
			$data['sort'] = $_REQUEST['sort'];
			$data['dir'] = $_REQUEST['dir'];
			$ps->event->_test->arg( array( &$data['userFilter'] ) , array(  $_REQUEST['userFilter'] ), 2, false );
			$data['user_id'] = $_SESSION['user_id'];
			
			if($valid) {
				$ps->event->setData($data);
				$records = $ps->event->listRecords();
				$total = $ps->event->total;
				$records = ($records == NULL) ? array() : $records;
				print_c( json_encode( array( 'success' => true, 'total' => $total, 'records' => $records ) ) );
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		case 'event-getlist':
			if(!$ps->event->_test->arg( array( &$data['field'] ) , array(  $_REQUEST['field'] ), 2,  'title', array( 'title', 'event_type', 'date_start', 'date_end' ) )) {
				$valid = false;
				$code = 4;
			}
			$data['value'] = $_REQUEST['value'];
			if(!$ps->event->_test->arg( array( &$data['sort'] ) , array(  $_REQUEST['sort'] ), 2,  	'asc', array( 'asc', 'desc' ) )) {
				$valid =false;
				$code = 5;
			}
			$ps->event->_test->arg( array( &$data['start'] ) , array(  $_REQUEST['start'] ), 2, '0' );
			$ps->event->_test->arg( array( &$data['limit'] ) , array(  $_REQUEST['limit'] ), 2, RECORDS_PER_PAGE );
			if($valid) {
				$ps->event->setData($data);
				$records = $ps->event->getList();
				$records = ($records == NULL) ? array() : $records;
				print_c( json_encode( array( 'success' => true, 'records' => $records ) ) );
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		case 'eventtype-getlist':
			if(!$ps->event->_test->arg( array( &$data['field'] ) , array(  $_REQUEST['field'] ), 2,  'title', array( 'polygon', 'title', 'description' ) )) {
				$valid = false;
				$code = 4;
			}
			$data['value'] = $_REQUEST['value'];
			if(!$ps->event->_test->arg( array( &$data['sort'] ) , array(  $_REQUEST['sort'] ), 2,  	'asc', array( 'asc', 'desc' ) )) {
				$valid =false;
				$code = 5;
			}
			$ps->event->_test->arg( array( &$data['start'] ) , array(  $_REQUEST['start'] ), 2, '0' );
			$ps->event->_test->arg( array( &$data['limit'] ) , array(  $_REQUEST['limit'] ), 2, RECORDS_PER_PAGE );
			
			if($valid) {
				$ps->event->setData($data);
				$records = $ps->event->getEventTypeList();
				$records = ($records == NULL) ? array() : $records;
				print_c( json_encode( array( 'success' => true, 'records' => $records ) ) );
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		case 'removeEvent':
			$removed = $ps->event->removeEvent($event_id, $_SESSION["user_id"]);
			if($removed) {
				print_c( json_encode( array('success' => true) ) );
			} else {
				$code = 12;
				print_c( json_encode( array('success' => false, 'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		case 'dwc-update':
//			if(!$user_access->is_logged_in()) {$code = 2; $valid = false;}
			if(trim($_REQUEST['col_id'])=='') {
				$valid = false; $code = 11;
			}
			$ps->waflora->load_by_id( $_REQUEST['col_id'] );
			$data = $ps->waflora->getDwcByIndex();

/*
			if(!$ps->dwc->_test->arg( array( &$data['GlobalUniqueIdentifier'] ) , array(  $_REQUEST['GlobalUniqueIdentifier'] ), 1 )) {
				$valid = false;
				$code = 8;
			}
*/			
			if(!$ps->dwc->_test->arg( array( &$data['land_id'] ) , array(  $_REQUEST['land_id'] ), 1 )) {
				$valid = false;
				$code = 9;
			}

			if(!$ps->land->recordExists($data['land_id'])) {
				$code = 10;
				$valid = false;
			}

			if($valid) {
				// check if already present
				$ar = array("condition" => "AND","items" => 
					array(
						array ("field"=>"CatalogNumber","condition"=>"EQUAL","value"=>"{$data['CatalogNumber']}"),
						array ("field"=>"land_id","condition"=>"EQUAL","value"=>"{$data['land_id']}")
					)
				);

				$id = $ps->dwc->checkRecord($ar);
				if($id !== false) {
					$data['Id'] = $id->ID;
				}
				$ps->dwc->setData($data);
				$ps->dwc->save();
				print_c( json_encode( array( 'success' => true ) ) );
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		case 'removeSpecies':
			$removed = $ps->dwc->removeSpecies($species_id, $_SESSION["user_id"]);
			if($removed) {
				print_c( json_encode( array('success' => true) ) );
			} else {
				$code = 11;
				print_c( json_encode( array('success' => false, 'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		case 'dwc-list':
			$data['filter'] = json_decode( stripslashes($filter), true );
			if(trim($_REQUEST['sort']) != '') {
				$data['order'][] = array( 'field' => $_REQUEST['sort'], 'dir' => $_REQUEST['dir'] );
			}
			$ps->dwc->_test->arg( array( &$data['start'] ) , array(  $_REQUEST['start'] ), 2, '0' );
			$ps->dwc->_test->arg( array( &$data['limit'] ) , array(  $_REQUEST['limit'] ), 2, RECORDS_PER_PAGE );
			$ps->event->_test->arg( array( &$data['userFilter'] ) , array(  $_REQUEST['userFilter'] ), 2, false );
			$data['user_id'] = $_SESSION['user_id'];

			if($valid) {
				$ps->dwc->setData($data);
				$columns = implode(",", array("land_id", "Kingdom", "Family", "Genus", "ScientificName", "Id") );
				$records = $ps->dwc->listRecords( $columns );
				$total = $ps->dwc->getTotal();
				$records = ($records == NULL) ? array() : $records;
				print_c( json_encode( array( 'success' => true, 'total' => $total, 'records' => $records ) ) );
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		case 'dwc-getlist':

			if(!$ps->dwc->_test->arg( array( &$data['field'] ) , array(  $_REQUEST['field'] ), 2,  'GlobalUniqueIdentifier' )) {
				$valid = false;
				$code = 4;
			}
			$data['value'] = $_REQUEST['value'];
			if(!$ps->dwc->_test->arg( array( &$data['sort'] ) , array(  $_REQUEST['sort'] ), 2,  	'asc', array( 'asc', 'desc' ) )) {
				$valid =false;
				$code = 5;
			}
			$ps->dwc->_test->arg( array( &$data['start'] ) , array(  $_REQUEST['start'] ), 2, '0' );
			$ps->dwc->_test->arg( array( &$data['limit'] ) , array(  $_REQUEST['limit'] ), 2, RECORDS_PER_PAGE );
			if($valid) {
				$ps->dwc->setData($data);
				$records = $ps->dwc->getList();
				$records = ($records == NULL) ? array() : $records;
				print_c( json_encode( array( 'success' => true, 'records' => $records ) ) );
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		case 'col-getlist':
		
			if(!$ps->dwc->_test->arg( array( &$data['name'] ) , array(  $_REQUEST['name'] ), 2 )) {
				$valid = false;
				$code = 4;
			}
			
			$ps->dwc->_test->arg( array( &$data['start'] ) , array(  $_REQUEST['start'] ), 2, '0' );
			$ps->dwc->_test->arg( array( &$data['limit'] ) , array(  $_REQUEST['limit'] ), 2, RECORDS_PER_PAGE );
			if($valid) {
				$ps->col->load_by_name($data['name']);
				$records = $ps->col->getNames();
				$records = ($records == NULL) ? array() : $records;
				print_c( json_encode( array( 'success' => true, 'records' => $records ) ) );
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		case 'waflora-getlist':
		
			if(!$ps->dwc->_test->arg( array( &$data['name'] ) , array(  $_REQUEST['name'] ), 2 )) {
				$valid = false;
				$code = 4;
			}
			
			$ps->dwc->_test->arg( array( &$data['start'] ) , array(  $_REQUEST['start'] ), 2, '0' );
			$ps->dwc->_test->arg( array( &$data['limit'] ) , array(  $_REQUEST['limit'] ), 2, RECORDS_PER_PAGE );
			if($valid) {
				$ps->waflora->load_by_name($data['name']);
				$records = $ps->waflora->getNames();
				$records = ($records == NULL) ? array() : $records;
				print_c( json_encode( array( 'success' => true, 'records' => $records ) ) );
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;


		/**
			@param optional
			output : json, csv, email
			start
			limit
			delimiter : COMMA,SEMICOLON,TAB,SPACE
			values
			filters
			email_email
			email_msg
		*/
		case 'checklist-region':
			$valid = true;
			$ps->dwc->time_start = microtime(true);
			$ps->dwc->_test->arg( array(&$data['start']), array($_REQUEST['start']), 2, 0 );
			$ps->dwc->_test->arg( array(&$data['limit']), array($_REQUEST['limit']),2, 100 );
			if (!$ps->dwc->_test->arg( array( &$data['output'] ) , array(  $_REQUEST['output'] ), 2, 'json', array('json','csv','email') )) {
				$code = 118;
				$valid = false;
			}

			if (!$ps->dwc->_test->arg( array( &$data['delimiter'] ) , array(  $_REQUEST['delimiter'] ), 2, 'COMMA', array('COMMA','SEMICOLON','TAB','SPACE') )) {
				$code = 131;
				$valid = false;
			}

			$data['filter'] = json_decode( stripslashes($filter), true );
			$data['values'] = stripslashes($_REQUEST['values']);
			$data['email_email'] = $_REQUEST['email_email'];
			$data['email_msg'] = $_REQUEST['email_msg'];

			if($valid) {
				$ps->dwc->setData($data);
				if($ps->dwc->loadCheckListRegion()) {
					switch (@strtolower($data['output'])) {
						case 'json':
							print_c(  $ps->dwc->getJSON('checklist-region') );
							break;
					}
				}
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		case 'checklist-event':
			$valid = true;
			$ps->dwc->time_start = microtime(true);
			$ps->dwc->_test->arg( array(&$data['start']), array($_REQUEST['start']), 2, 0 );
			$ps->dwc->_test->arg( array(&$data['limit']), array($_REQUEST['limit']),2, 100 );
			if (!$ps->dwc->_test->arg( array( &$data['output'] ) , array(  $_REQUEST['output'] ), 2, 'json', array('json','csv','email') )) {
				$code = 118;
				$valid = false;
			}

			if (!$ps->dwc->_test->arg( array( &$data['delimiter'] ) , array(  $_REQUEST['delimiter'] ), 2, 'COMMA', array('COMMA','SEMICOLON','TAB','SPACE') )) {
				$code = 131;
				$valid = false;
			}

			$data['values'] = stripslashes($_REQUEST['values']);

			$data['filters'] = $_REQUEST['filters'];
			$data['filter'] = stripslashes($filter);
			$data['email_email'] = $_REQUEST['email_email'];
			$data['email_msg'] = $_REQUEST['email_msg'];
			$data['start_date'] = $_REQUEST['start_date'];
			$ps->dwc->_test->arg( array(&$data['end_date']), array($_REQUEST['end_date']), 2, date('Y-m-d') );

			$data['start_date'] = stripslashes($data['start_date']);
			$data['end_date'] = stripslashes($data['end_date']);

			if($valid) {
				$ps->dwc->setData($data);
				if($ps->dwc->loadCheckListEvent()) {
					switch (@strtolower($data['output'])) {
						case 'json':
							print_c( $ps->dwc->getJSON('checklist-event') );
							break;
					}
				}
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		case 'species-land':
			if (!$ps->dwc->_test->arg( array( &$data['output'] ) , array(  $_REQUEST['output'] ), 2, 'json', array('json','csv','email') )) {
				$code = 118;
				$valid = false;
			}
			if($valid) {
				$cnt = $ps->dwc->getTotalSpecies();
				if($cnt) {
					if($ps->dwc->getSpeciesLand($cnt)) {
						switch(@strtolower($data['output'])) {
							case 'json':
								print_c( $ps->dwc->getJSON('species-land') );
								break;
						}
					}
				}
			} else {
				print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error($code) , 'code' => $code ) ) ) );
			}
			break;

		default:
			print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $ps->error(1) , 'code' => 1 ) ) ) );
			break;

	}
} else {
	print_c( json_encode( array( 'success' => false, 'error' => array('msg' => 'Error in Connection', 'code' => 1 ) ) ) );
}

/*
*	Function print_c (Print Callback)
*	This is a wrapper function for print that will place the callback around the output statement
*/
function print_c( $str ) {
	header('Content-type: application/json');
	if ( isset( $_REQUEST['callback'] ) ) {
		$cb = $_REQUEST['callback'] . '(' . $str . ')';
	} else {
		$cb = $str;
	}
	print $cb;
}

function myErrorHandler($errno, $errstr, $errfile, $errline) {
	switch ($errno) {
		case E_USER_ERROR:
			$msg = "ERROR [$errno] $errstr<br />";
			$msg .= "  Fatal error on line $errline in file $errfile";
			$msg .= ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />";
			$msg .= "Aborting...<br />";
			print_c( json_encode( array( 'success' => false,  'error' => array('msg' => $msg , 'code' => $errno ) ) ) );
			exit(1);
			break;
	}
}

?>